//
//  XPStackView.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/19.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

enum XPStackViewButtonType: Int {
    case Picture = 0
    case Mention = 1
    case Trend = 2
    case Emoticon = 3
    case Add = 4
}

class XPStackView: UIStackView {
    
    var emojiButton: UIButton?
    var isSelectedEmojiButton = false
    var seletedButtonClosure: ((buttonType: XPStackViewButtonType) -> Void)?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        axis = .Horizontal
        distribution = .FillEqually
        addSubview("compose_toolbar_picture", type: .Picture)
        addSubview("compose_mentionbutton_background", type: .Mention)
        addSubview("compose_trendbutton_background", type: .Trend)
        emojiButton = addSubview("compose_emoticonbutton_background", type: .Emoticon)
        addSubview("compose_add_background", type: .Add)
    }
    
    private func addSubview(imageName: String, type: XPStackViewButtonType) -> UIButton {
        let button = UIButton()
        button.addTarget(self, action: #selector(XPStackView.selectedButton(_:)), forControlEvents: .TouchUpInside)
        button.tag = type.rawValue
        button.setImage(UIImage(named: imageName), forState: .Normal)
        button.setImage(UIImage(named: imageName + "_highlighted"), forState: .Highlighted)
        button.backgroundColor = UIColor(patternImage: UIImage(named: "compose_toolbar_background")!)
        addArrangedSubview(button)
        return button
    }
    
    @objc private func selectedButton(button: UIButton) {
        let type = XPStackViewButtonType(rawValue: button.tag)!
        seletedButtonClosure?(buttonType: type)
        if type == .Emoticon {
            isSelectedEmojiButton = !isSelectedEmojiButton
            showEmojiKeyboard(isSelectedEmojiButton)
        }
    }
    
    private func showEmojiKeyboard(isEmojiKeyboard: Bool) {
        var icon = "compose_emoticonbutton_background"
        if isEmojiKeyboard {
            icon = "compose_keyboardbutton_background"
        }
        emojiButton?.setImage(UIImage(named: icon), forState: .Normal)
        emojiButton?.setImage(UIImage(named: "\(icon)_highlighted"), forState: .Highlighted)
    }
}
